<template>
    <view class="content">
        <van-nav-bar :title="title" left-arrow @click-left="onClickLeft" id="navBar"> </van-nav-bar>
        <!-- <loading :loadingIsShow="loadingIsShow"></loading> -->
        <view class="main-container">
            <scroll-view :refresher-enabled="false" class="scroll-content" @scroll="scrollPage" scroll-y
                :lower-threshold="120" @scrolltolower="loadMore" show-scrollbar="false">

                <view class="scroll-box">
                    <view class="reviewWrapper">
                        <!-- <view class="title">最新评论</view> -->
                        <!-- 评论列表 -->
                        <view class="reviewList" v-if="hasData">
                            <view class="comment-item" v-for="(item,index) in comments" :key="index" >
                                <view @tap="toJudgeDetail(item)">
                                    <view class="user-info">
                                        <view class="user-info-left" style="display: flex; align-items: center;">
                                            <img :src="item.wxUserInfo.avatarUrl ? item.wxUserInfo.avatarUrl : defaultAvatarUrl"
                                                alt="">
                                            <view class="user-name">{{ item.wxUserInfo.nickName }}</view>
                                        </view>
                                        <template v-show="false">
                                            <van-button size="mini" class="guanzhu" type="default">{{ item.currentUserFollow == true ? '已关注' : '关注' }}</van-button>
                                        </template>
                                    </view>
                                    <view class="comment-content">{{ item.content }}</view>
                                    <!-- <view class="comment-content" v-if="index!==0"><span class="_parentRelyNickName">@{{ item.parentWxUserInfo.nickName }}</span>:<span>{{item.content}}</span></view> -->
                                </view>
                                <view class="image-container"
                                    v-if="item.attachment && item.judgeImages.length > 0" @tap="toJudgeDetail(item)">
                                    <view class="imgInfo" v-for="(i, j) in item.judgeImages.slice(0, 4)" :key="j">
                                        <img width="330rpx" height="330rpx" :src="i" />
                                    </view>
                                </view>
                                <view class="comment-footer">
                                    <view class="time" @tap="toJudgeDetail(item)">{{ item.formattedPublishTime }}</view>
                                    <view class="interaction">
                                        <view @tap="toJudgeDetail(item)" style="display: flex; align-items: center;">
                                            <van-icon name="chat-o" style="margin-right: 8rpx;" size="12" />
                                            <view class="count" style="margin-right:40rpx;">{{ item.commentCount }}</view>
                                        </view>
                                        <view style="margin-right: 8rpx;" @tap.stop="handlerLike(item)">
                                            <van-icon name="good-job-o" size="15" style="color:#888888 !important;"
                                                v-if="!item.currentUserLike" />
                                            <van-icon name="good-job" size="15" style="color:#FF6203 !important;"
                                                v-if="item.currentUserLike" />
                                        </view>
                                        <view class="count">{{ item.likeCount }}</view>
                                    </view>
                                </view>
                            </view>
                            <view v-if="loading" class="loading-text">正在加载...</view>
                            <view v-if="finished" class="no-more-text">没有更多了</view>
                        </view>
                        <view class="reviewList" v-else>暂无评价</view>
                    </view>
                </view>
            </scroll-view>
        </view>

    </view>
</template>
  
<script>
import { topStyleWhite, topStyleBlack } from '@/utils/topColor'
import {getCommentListApi} from '@/api/activity'
import { likeCommentApi } from '@/api/judge' // 导入点赞接口
import { formatRelativeTime } from '@/utils/time-format-utility';


export default {
    components: {

    },
    data () {
        return {
            
            title: '活动评价',
            comments: [
                // {
                //     avatar: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/my/info.png',
                //     name: '赵楠',
                //     follow: false,
                //     content: '带上我的无压在一起吧，我需要呼吸山间的空气！',
                //     images: [
                //         'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/my/info.png',
                //         'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/my/info.png',
                //         'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/my/info.png',
                //     ],
                //     time: '刚刚',
                //     commentCount: 19,
                //     likeCount: 19
                // },
                // {
                //     avatar: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/my/info.png',
                //     name: 'Cool Marlon',
                //     follow: true,
                //     content: '25年春节档有多部大片上映，如《封神榜》《哪吒2》《射雕英雄传之侠之大者》，我个人最推荐的肯定就是《哪吒2》。',
                //     images: [
                //         'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/self_pickup.png',
                //         'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/self_pickup.png',
                //         'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/self_pickup.png',
                //         'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/self_pickup.png'
                //     ],
                //     time: '50分钟前',
                //     commentCount: 19,
                //     likeCount: 19
                // }
            ],
            params:{},  //路由参数
            productId:undefined,
            isFollowUp: undefined,
            isPic: undefined,
            sortField:'comprehensive',  //排序类型，综合（comprehensive）、最新（last）、回头客（repeatBuy）
            timeDiffResult:'',
            replyId:undefined,
            comments:[],  //评论列表
            pageNum:1,
            pageSize:10,
            total:0,
            activitiesId:undefined,  //活动ID
            loading: false,
            finished: false,
            hasData:false,  //是否有数据
            pageType:undefined,  //页面类型，1：活动评价，2：活动详情
        }
    },
    computed: {
        // preCalculatedTimeDiff() {
        //     return this.timeDiffResult; // 在模板中直接使用提前计算好的结果
        // }
    },
    filters: {
        // timeFormatDay(time1) {
        //     console.log('time1', time1)
        //     return timeFormatDay(time1)
        // },
        // timeFormat(time1){
        //     console.log('time1', time1)
        //     return timeFormat(time1)
        // },
        // formatDateSE(timeStr) {
        //     console.log(timeStr,'timeStr')
        //     if (timeStr !== null && timeStr !== undefined) {
        //         // const timeA=timeStr.replace(/-/g, '/')
        //         const timeStrss = timeStr.replace('+0000', '');
        //         const date = new Date(timeStrss);
        //         const year = date.getFullYear();
        //         const month = ("0" + (date.getMonth() + 1)).slice(-2);
        //         const day = ("0" + date.getDate()).slice(-2);
        //         const weekDay = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][date.getDay()];
        //         const hours = ("0" + date.getHours()).slice(-2);
        //         const minutes = ("0" + date.getMinutes()).slice(-2);
        //         const formatDate = `${year}.${month}.${day}  ${hours}:${minutes}`
        //         return formatDate;
        //     } else {
        //         console.error('传入的startTime格式不正确，期望为合法数字类型的时间戳');
        //         return ''
        //     }

        // },

        // toimg(text) {
        //     return weixinMojiTranslate(text)
        // }
    },
    onLoad (data) {
    // 取到路由携带的参数
        if (data && data.params) {
            this.params = JSON.parse(decodeURIComponent(data.params))
            console.log(JSON.parse(decodeURIComponent(data.params)))
            console.log('params', this.params)
            this.activitiesId=this.params.activitiesId
        }
    },
    onReady () {

    },
    onShow() {
        this.getCommentListMethod()
    },
    methods: {
        formatTime(timestamp) {
            return formatRelativeTime(timestamp);
        },
        // 互动页面
        scrollPage(e) {
            // console.log(e.detail.scrollTop, this.scrolling)
            // if (e.detail.scrollTop > 1 && !this.scrolling) {
            //     this.scrolling = true
            // } else if ((e.detail.scrollTop <= 1 && this.scrolling) || (e.detail.scrollTop <= 1 && !this.scrolling)) {
            //     this.scrolling = false
            // }
        },
        // 新增加载更多方法
        loadMore() {
            if (!this.finished) {
                this.getCommentListMethod();
            }
        },

        calculateTimeDiff(time1,time2) {
            console.log(time1,'time1',time2,'time2')
            var time = new Date(time1.replace(/-/g, '/').replace('+0000', '')).getTime()
            var timess2=new Date(time2.replace(/-/g, '/').replace('+0000', '')).getTime()
            console.log(time,timess2,'time')
            // debugger
            if (time > 0) {
                var result
                time = parseInt(time)
                var minute = 1000 * 60
                var hour = minute * 60
                var day = hour * 24
                var month = day * 30
                // var now = new Date().getTime()
                var diffValue = time - timess2
                if (diffValue < 0) {
                    return
                }
                var monthC = diffValue / month
                var weekC = diffValue / (7 * day)
                var dayC = diffValue / day
                var hourC = diffValue / hour
                var minC = diffValue / minute

                if (monthC >= 1) {
                    if (monthC <= 12) {  //未超过一年  08-09 11:09:09
                     result = '' + parseInt(dayC) + '天后'
                    } else { //超过一年  2022-08-25 11:26:09
                    result =time1
                    }
                } else if (weekC >= 1) {
                    result = '' + parseInt(dayC) + '天后'
                } else if (dayC >= 1) {
                    result = '' + parseInt(dayC) + '天后'
                } else if (hourC >= 1) {
                     result = '' + 1 + '天内'
                } else if (minC >= 1) {
                    result = '' + parseInt(minC) + '分钟内'
                } else {
                    // result = '刚刚'
                    result = '' + 1 + '分钟内'
                }
                return result
            } else {
                return ''
            }
        },
        // 返回按钮
        onClickLeft () {
            uni.navigateBack()
        },

        // // 第一行
        // changeSort(index,e,name){
        //     this.currentPIndex = index
        //     console.log(index,e)
        //     if(name.includes('图') ||index===2){
        //         this.isPic=true
        //         this.isFollowUp=undefined
        //     }else if(name.includes('追评')||index===1){
        //         this.isFollowUp=true
        //         this.isPic=undefined
        //     }else{
        //         this.isPic=undefined
        //         this.isFollowUp=undefined
        //     }
        //     this.getProductReplyById()

        // },
        // // 第二行
        // selectFilter(val,e,name){
        //     this.curFilter=val
        //     console.log(val,e,name,'评论列表第二行tab')
        //     if(val===0){
        //         this.sortField='comprehensive'
        //     }else if(val===1){
        //         this.sortField='last'
        //     }else{
        //         this.sortField='repeatBuy'
        //     }
        //     this.getProductReplyById()
        // },
        // // 显示弹窗
        // onClickSort () {
        //     this.popupShow = true
        //     topStyleWhite()
        // },
        // // 隐藏弹窗
        // closePopup () {
        //     this.popupShow = false
        //     topStyleBlack()
        // },

        // 跳转用户详情
        toJudgeDetail(item){
            const params = {
                pageSymbol:'commentList',
                replyId:item.id,
                activitiesId:this.activitiesId,
                pageType:this.params.pageType,
            }
            uni.navigateTo({
                url:
                    '/pages/activityComment/commentDetails?params=' +
                    encodeURIComponent(JSON.stringify(params))
            })
        },

        // 是否为null
        areAllNull(...args) {
            return args.every(arg => arg === null);
        },

        // 都不为null
        notAreAllNull(...args) {
            return args.every(arg => arg !== null);
        },
        // 活动评论点赞
        // 点赞
        handlerLike(item) {
            item.currentUserLike = !item.currentUserLike
            if (item.currentUserLike) {
                item.likeCount++
            } else {
                item.likeCount--
            }
            this.replyId = item.id
            this.likeComment(item.id)
        },

        // 判断是否有图片
        handleImages(pics) {
            // 判断追评中是否有图片的逻辑
            let isPics;
            if (pics !== null && pics !== '' && pics !== undefined) {
                isPics = true;
            } else {
                isPics = false;
            }
            return isPics;
        },
        /**
         * 接口
         */
        // 获取评论列表
        getCommentListMethod () {
            if (this.loading || this.finished) return;
            this.loading = true;
            
            const params ={
                pageNum:this.pageNum,
                pageSize:this.pageSize,
                activitiesId:this.activitiesId,  //活动ID
                // commentId:undefined,  //评论ID
            }
            return new Promise((resolve, reject) => {
                getCommentListApi(params).then((res) => {
                    console.log(res)
                    if (res.code === 200) {
                        this.total = res.data.total;
                        // 修改数据合并方式
                        const processedList = res.data.list.map(item => ({
                            ...item,
                            formattedPublishTime: this.formatTime(item.publishTime)
                        }));

                        // 修改点2: 正确合并分页数据
                        this.comments = this.pageNum === 1
                            ? processedList
                            : [...this.comments, ...processedList];
                        // 处理图片数据
                        this.comments.forEach(item => {
                            if (item.attachment) {
                                item.judgeImages = item.attachment.split(',') || []
                            } else {
                                item.judgeImages = []
                            }
                            console.log(item.judgeImages,'item',item)
                        })
                        this.finished = this.comments.length >= this.total;
                        this.pageNum++;
                        console.log(this.comments, 'this.orderList')
                        this.hasData = this.comments.length > 0
                        resolve(res)
                    } else {
                        reject(res)
                    }
                }).finally(() => {
                    this.loading = false;
                })
            })
        },
        // 点赞  取消点赞
        likeComment(replyId){
            return new Promise((resolve, reject) => {
                const params={
                    commentId:replyId,
                    interactionsTargetType:'post'
                }
                likeCommentApi(params).then((res) => {
                    console.log(res)
                    if (res.code === 200) {
                        console.log('res-----', res.data)
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },
     
    }
}
</script>
    
<style lang="scss" scoped>
.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100vh;
    overflow: hidden;
    z-index: -2;
    background-color: #ffffff;
    background-size: 100%;

}

.main-container {
    background-color: #ffffff;
    height: 100vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}


// .topBox {
//     background: #ffffff;
//     // position: fixed;
//     // z-index: 999;
//     // width: 100%;
//     // padding: 20px 18px 12px 18px;
//     padding: 10px 24px 10px 24px;
//     // background: pink;

//     // 全部分类  menu
//     .sort-menu {
//         // margin-bottom: 23px;  //放到下一行的 综合 按钮部分
//         display: flex;


//         .sort_option {
//             //   flex: 1;
//             // font-weight: bolder;
//             line-height: 14px;
//             font-size: 14px;
//             text-align: left;
//             color: #666666;
//             margin-right: 39px;
//         }

//         .sort_option_selected {
//             // font-weight: 900;
//             font-weight: bolder;
//             text-align: left;
//             color: #111111;
//             font-size: 18px;
//             line-height: 18px;
//         }
//     }
// }

// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}

.scroll-box {
    height: 100vh;
    background: #ffffff;
}
// 评论
.reviewWrapper {
        padding: 40rpx 48rpx;

    .comment-item {
        margin-bottom: 66rpx;
        background-color: white;
        border-radius: 8rpx;
        overflow: hidden;
    }

    .user-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .user-info-left {
            display: flex;
            align-items: center;
            
            img{
                width: 80rpx;
                height: 80rpx;
                border-radius: 50%;
                margin-right: 24rpx;
            }
        }
    }

    .user-name {
        // margin-left: 10rpx;
        font-size: 28rpx;
        text-align: left;
        color: #333;
    }

    .comment-content {
        margin-top: 24rpx;
        font-weight: 400;
        font-size: 32rpx;
        line-height: 48rpx;
        text-align: left;
        color: #333;
        ._parentRelyNickName{
            color: #ff6203;
        }
    }

    .image-container {
        margin-top: 24rpx;
        display: flex;
        flex-wrap: wrap;
        // height: 330rpx;
        width: 100%;
        // gap: 5rpx; /* 新增间距 */
        .imgInfo{
            // width: calc(50% - 5rpx); /* 调整宽度适配间隙 */
            width:calc((100% - 10rpx) / 2);
            overflow: hidden; /* 防止图片溢出 */
            margin-bottom:10rpx;
        }
        img{
            height: 330rpx;
            width: 100%;
        }
        .imgInfo:nth-child(2n) {
            margin-bottom: 0rpx; /* 调整下间距 */
        }
    }

    .comment-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10rpx;
        font-size: 24rpx;
        color: #999;
    }
    .comment-footer .time{
        font-weight: 400;
        font-size: 24rpx;
        text-align: left;
        color: #999;
    }

    .interaction {
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 24rpx;
        text-align: left;
        color: #333;
    }

    .more-comments {
        text-align: center;
        margin-top: 40rpx;
        padding-bottom: 114rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 400;
        font-size: 28rpx;
        text-align: left;
        color: #ff6203;
    }
}
.loading-text, .no-more-text {
    padding: 20rpx;
    text-align: center;
    color: #888;
    font-size: 24rpx;
}
::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep #navBar .van-icon {
    color: #242629 !important;
}


::v-deep .van-nav-bar__title {
    font-size: 14px;
    color: #333333;
}

::v-deep .van-empty {
    background: transparent;
    border-radius: 12px;
}

::v-deep .van-empty__image {
    width: 164px;
    height: 164px;
}


.pl15 {
    padding-left: 15px;
}

.b12 {
    margin-bottom: 12px;
}

.t12 {
    margin-top: 12px;
}
</style>
    